package com.uxhao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.uxhao.commonutils.R;
import com.uxhao.eduservice.client.VodClient;
import com.uxhao.eduservice.entity.EduVideo;
import com.uxhao.eduservice.mapper.EduVideoMapper;
import com.uxhao.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uxhao.servicebase.exceptionhandler.QLLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author uxhao
 * @since 2022/01/11
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;//微服务调用

    /**
     * 根据章节id查询小节是否有数据
     * @param id 章节id
     * @return
     */
    @Override
    public boolean getCountByChapterId(String id) {
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return null != count && count > 0;
    }

    //根据课程id删除小节
    @Override
    public void removeVideoByCourseId(String courseId) {
        //TODO  批量删除视频[已完成]
        //根据课程id查询所有视频列表
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.select("video_source_id");
        List<EduVideo> videoList = this.list(queryWrapper);

        List<String> videoIds = videoList.stream().map(EduVideo::getVideoSourceId).collect(Collectors.toList());

        if (videoIds.size()>0){
            vodClient.removeVideoList(videoIds);
        }


        QueryWrapper<EduVideo> videoWrapper=new QueryWrapper<>();
        videoWrapper.eq("course_id",courseId);
        this.remove(videoWrapper);

    }

    //TODO 删除小节下的视频
    //根据小节id删除小节和视频
    @Override
    public boolean removeVideoById(String id) {
        // 根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = this.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();

        // 判断小节里面是否有视频id
        if(!StringUtils.isEmpty(videoSourceId)){
            // 根据视频id,远程调用实现视频删除
            R result = vodClient.removeVideo(videoSourceId);
            if(result.getCode() == 20001){
                throw new QLLException(20001,"删除视频失败，熔断器...");
            }
        }
        return this.removeById(id);
    }
}
